package com.github.editor.util;

import javax.net.ssl.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;

public class HttpUtil {
    private static class MyX509TrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    public static boolean download(String urlStr, String savePath) {
        HttpURLConnection conn;
        int code;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(20 * 1000);
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.9 Safari/537.36");
            if (urlStr.startsWith("https")) {
                SSLContext sslContext = SSLContext.getInstance("SSL");
                TrustManager[] tm = {new MyX509TrustManager()};
                sslContext.init(null, tm, new java.security.SecureRandom());
                SSLSocketFactory ssf = sslContext.getSocketFactory();
                ((HttpsURLConnection) conn).setSSLSocketFactory(ssf);
            }
            code = conn.getResponseCode();
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
        if (code >= 200 && code < 300) {
            File dir = new File(savePath).getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            try (InputStream inputStream = conn.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(savePath)) {
                FileUtil.copy(inputStream, outputStream);
            } catch (Throwable e) {
                //ignore
                return false;
            } finally {
                conn.disconnect();
            }
        } else {
            conn.disconnect();
        }
        return true;
    }
}
